﻿using UnityEngine;
using UnityEngine.UI;

public class FadeOut : MonoBehaviour
{
    public float fadeIn = 0.5f;
    public float maintain = 2f;
    public float fadeOut = 0.5f;

    Text text;
    Color col;
    float startTime;
    float processTime;
    Color startCol;
    Color endCol;

    enum FadeType
    {
        Stay,
        In,
        WaitOut,
        Out,
    }
    FadeType ft = FadeType.Stay;

    void Awake()
    {
        text = GetComponent<Text>();
        col = text.color;
    }

    public void FadeBegin(bool bIn)
    {
        var zero = col;
        zero.a = 0f;
        if (bIn)
        {
            text.color = zero;
            startCol = zero;
            endCol = col;
            startTime = Time.time;
            processTime = fadeIn;
            ft = FadeType.In;
        }
        else
        {
            text.color = col;
            startCol = col;
            endCol = zero;
            startTime = Time.time;
            processTime = fadeOut;
            ft = FadeType.Out;
        }
    }

#if UNITY_EDITOR
    [ContextMenu("In")]
    public void Test()
    {
        FadeBegin(true);
    }

    [ContextMenu("Out")]
    public void Test2()
    {
        FadeBegin(false);
    }
#endif

    // Update is called once per frame
    void Update ()
    {
        switch (ft)
        {
            case FadeType.In:
                {
                    var pass = Time.time - startTime;
                    text.color = Color.Lerp(startCol, endCol, pass / processTime);
                    if (pass >= processTime)
                        ft = FadeType.WaitOut;
                }
                break;
            case FadeType.WaitOut:
                {
                    var pass = Time.time - startTime;
                    if (pass >= maintain)
                        FadeBegin(false);
                }
                break;
            case FadeType.Out:
                {
                    var pass = Time.time - startTime;
                    text.color = Color.Lerp(startCol, endCol, pass / processTime);
                    if (pass >= processTime)
                        ft = FadeType.Stay;
                }
                break;
            default:
                break;
        }
	}
}
